package com.bigdatastudio.api.Upload;

import com.bigdatastudio.common.Utils.FileUtil;
import com.bigdatastudio.common.Utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 对象存储 前端控制器
 * </p>
 *
 * @author PC
 * @since 2022-10-16
 */
@RestController
@RequestMapping("/api/file")
@RefreshScope
public class OssController {

    @Autowired
    private IOssService ossService;

    @Resource
    private HttpServletResponse response;

    @Resource
    private HttpServletRequest request;

    @Value("${reggie.path}")
    private String staticPath;

    @GetMapping(value = "test")
    public R local(){
        return R.ok(staticPath,"数据得到成功！！");
    }


    @CrossOrigin(methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
    @PostMapping("uploadImg")
    public String  uploadMarkdownImg(MultipartFile file)throws Exception{
        return ossService.uploadImg(file);
    }

    @CrossOrigin(methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
    @PostMapping("uploadMarkdownImg")
    public String  uploadMarkdownImg(MultipartHttpServletRequest multiRequest)throws Exception{
        return ossService.uploadMarkdownImg(multiRequest);
    }

    /**
     * 本地文件下载
     * @param filename
     * @throws IOException
     */
    @GetMapping(value = "localDownload")
    public void localDownload(@RequestParam("filename") String filename) throws IOException {
        StringBuilder fileOriginName = new StringBuilder(filename);
        int lastIndex =fileOriginName.lastIndexOf("/");
        fileOriginName.delete(0,lastIndex+1);
        // 文件本地位置
        String filePath = staticPath+"/"+fileOriginName;
        // 文件名称
        File file = new File(filePath);
        FileUtil.downloadFile(file, request, response, String.valueOf(fileOriginName));
    }

    /**
     * 网络文件下载
     * @param urlStr
     * @throws IOException
     */
    @GetMapping(value = "httpDownload")
    public void httpDownload(@RequestParam("urlStr") String urlStr) throws IOException {
        StringBuilder fileOriginName = new StringBuilder(urlStr);
        int lastIndex =fileOriginName.lastIndexOf("/");
        fileOriginName.delete(0,lastIndex+1);
        FileUtil.downloadHttpFile(urlStr, request, response, String.valueOf(fileOriginName));
    }
}
